#!/bin/bash
set -e
PWD=$(pwd)
WORK_DIR="bin/targets/x86/64"
ISO_CONTENT="bin/targets/x86/64/iso_content"
CPIO_DIR="bin/targets/x86/64/cpio"

echo "Init iso env"
rm -rf $ISO_CONTENT
mkdir -p $ISO_CONTENT
rm -rf $CPIO_DIR
cp -rf ./cpio $WORK_DIR
cp -rf ./boot $ISO_CONTENT


cd $WORK_DIR

# copy openwrt-x86-64-generic-rootfs.tar.gz
echo "copy openwrt-x86-64-generic-rootfs.tar.gz"
tar -xzf openwrt-x86-64-generic-rootfs.tar.gz -C iso_content

# truncate squashfs img and make a install image
echo "truncate squashfs img and make a install image"
rm -f sdwan_install_image.img
rm -f openwrt-x86-64-generic-squashfs-combined.img
gunzip -c openwrt-x86-64-generic-squashfs-combined.img.gz > openwrt-x86-64-generic-squashfs-combined.img || true
dd if=openwrt-x86-64-generic-squashfs-combined.img of=sdwan_install_image.img bs=1M count=60

rm -f sdwan_install_image.img.gz
gzip sdwan_install_image.img
cp sdwan_install_image.img.gz cpio/usr/sbin

# make a new cpio fs
rm -f sdwan_install.cpio.gz
echo "make new cpio fs"
cd cpio
find . | cpio -o -H newc > ../sdwan_install.cpio && gzip ../sdwan_install.cpio
cd ..
cp sdwan_install.cpio.gz iso_content/initrd.img

# gen iso image
cat <<EOF >> iso_content/boot/grub/grub.cfg
menuentry "Install SDWAN System" {
    linux /boot/vmlinuz root=/dev/ram0 ramdisk_size=1000000 init=/init console=tty1 console=ttyS0,115200n8 SYSTEMD_VCONSOLE=KEYMAP=us FONT=latarcyrheb-sun16 LANG=zh_CN.UTF-8
    initrd /initrd.img
}
EOF

rm -f sdwan_install.iso

xorriso -as mkisofs -o sdwan_install.iso     -b boot/grub/eltorito.img     -no-emul-boot -boot-load-size 4 -boot-info-table     --grub2-boot-info --grub2-mbr /usr/lib/grub/i386-pc/boot_hybrid.img     iso_content/

rm -f sdwan_install.cpio.gz sdwan_install_image.img.gz

echo -e "ISO IMAGE: \e[33m$WORK_DIR/sdwan_install.iso\e[0m"

cd $PWD
